from flask import Flask, jsonify, request
from flask_cors import CORS
import json
from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///clickDataBase/DataRes/click.db', echo=True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

class Click(Base):
    __tablename__ = 'click'
    id = Column(String, primary_key=True)
    click_list = Column(PickleType)

Base.metadata.create_all(engine)

app = Flask(__name__)
CORS(app, resources={
    r"/": {
        "origins": "*",
    }
})

@app.route('/getX', methods=['GET'])
def get_click():
    # 处理GET请求
    data = request.json
    url=data.get('url')
    print(f"Received GET request: {url}")
    click_node = session.query(Click).filter_by(id=url).first()
    click_list = click_node.click_list if click_node else None
    if click_list:
        print(click_list, "success")
        return jsonify(click_list)
    else:
        new_click=Click(id=url,click_list=[0]*100)
        session.add(new_click)
        session.commit()
        return jsonify([0]*100)

@app.route('/getX', methods=['POST'])
def post_click():
    data = request.json
    url=data.get('url')
    print(f"Received POST request: {url}")
    location=data.get('input_interger')
    click_node = session.query(Click).filter_by(id=url).first()
    click_list = click_node.click_list
    if click_list:
        click_list[location-1]+=1
        session.commit()
        print("success update cicklist")
    else:
        new_click=Click(id=url,click_list=[0]*100)
        session.add(new_click)
        session.commit()
        print("success add cicklist")


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(start_server)
    loop.run_forever()
